﻿using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Management.Automation;
using Microsoft.SharePoint;
using Microsoft.SharePoint.PowerShell;

using Microsoft.Office.Server.Search.Administration;
using Microsoft.Office.Server.Search.Cmdlet;

namespace Community.SharePoint.PowerShell
{
    /// <summary>
    /// SharePoint PowerShell Community Kit
    /// Get-SPEnterpriseSearchQueryScopeDisplayGroupScope
    /// This cmdlet gets a display group given a site collection
    /// URL and SearchServiceApplicationPipeBind
    /// Example (Gets a scope display group called "Search Dropdown"): 
    /// $searchapp = Get-SPEnterpriseSearchServiceApplication "Search Service Application"
    /// $group = Get-SPEnterpriseSearchQueryScopeDisplayGroup -Name "Search Dropdown" -url http://sp2010 -SearchApplication $searchapp
    /// Author: Peter Cuttriss (petecuttriss)
    /// Creation Date: 8/10/2010
    /// </summary>
    [Cmdlet(VerbsCommon.Get, "SPEnterpriseSearchQueryScopeDisplayGroup")]
    public class GetEnterpriseSearchQueryScopeDisplayGroup : SPGetCmdletBase<ScopeDisplayGroup>
    {
        [Parameter(Mandatory = true, Position = 1)]
        public string Name { get; set; }

        [Parameter(Mandatory = true), Alias(new string[] { "o" })]
        public Uri Url { get; set; }

        [Parameter(Mandatory = true, ValueFromPipeline = true, Position = 0)]
        public SearchServiceApplicationPipeBind SearchApplication { get; set; }

        protected override IEnumerable<ScopeDisplayGroup> RetrieveDataObjects()
        {
            List<ScopeDisplayGroup> list = new List<ScopeDisplayGroup>();

            // get the search applicatioin from the pipe bind
            SearchServiceApplication searchServiceApplication = SearchApplication.Read();

            Scopes scopes = new Scopes(searchServiceApplication);
            try
            {
                if (scopes.GetDisplayGroup(Url, Name) != null)
                {
                    list.Add(scopes.GetDisplayGroup(Url, Name));
                }
            }
            catch (InvalidCastException invEx)
            {
                throw new InvalidCastException("The scope display group " + Name + " does not exist.", invEx);
            }

            return list;
        }
    }
}